<?php
namespace app\index\controller;
use think\Controller;
use  GuzzleHttp\Client  as Guzzle;
use logink\loginkHelper as logink;
use util\Returnutil;
use util\RequestUtil;
use util\XmlHelper;
use think\Db;

class Index extends Controller
{
    public function index()
    {
        echo 'code:403';
    }

    public function hello($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }


    //处理云合同的回调业务
    public function yunHetongCallBack()
    {
        $content = @file_get_contents('php://input');

        //过滤不是三方的
        $title = json_decode($content,256)['content'];
        $sub_title = mb_substr($title,0,6);
        if ($sub_title != '运输三方协议') {
            return;
        }
        $client = new Guzzle([
            'base_uri' => 'http://118.190.207.192:91/',
        ]);
        $res = $client->request('POST','AgreeMent/yunReturn',[
            'body' => $content,
        ]);

        $returnStr = $res->getBody()->getContents();

    }

    public function testXml(logink $loginkHelper)
    {
        $return = Returnutil::getInstance();

        //@todo 请注意会换成post检测
        if ($this->request->isGet()) {

            try {

                $res = $loginkHelper->sendDemo();

                return $return->setCode(200)->setMessage('上报数据成功')->setData($res)->asJson();

            } catch (\Exception $e) {

                return $return->setCode(101)->setMessage($e->getMessage())->asJson();

            }

        } else {

            return $return->setCode(300)->setMessage('请求方式错误')->asJson();

        }
    }

    public function send(logink $loginkHelper)
    {
        $return = Returnutil::getInstance();

        if ($this->request->isPost()) {

            try {
                $ShippingNoteNumber = RequestUtil::post('ShippingNoteNumber','','trim');

                if (!$ShippingNoteNumber) {
                    throw new \Exception('ShippingNoteNumber格式错误');
                }

                $action = RequestUtil::post('ActionType','','trim');

                if (!in_array($action,config('app.logink.action'))) {
                    throw new \Exception('ActionType不存在的操作类型');
                } else {
                    if ($action == 'LOGINK_CN_FREIGHTBROKER_WAYBILL') {
                        $DocumentName = '无车承运人电子路单';
                        $prefix = 'WB';
                    } elseif ($action == 'LOGINK_CN_FREIGHTCHARGES') {
                        $DocumentName = '资金流水单';
                        $prefix = 'FC';
                    }
                }

                $json = RequestUtil::post('xmlJson','','trim');
                $json_arr = json_decode($json,true);
                if (!$json_arr) {
                    throw new \Exception('xmlJson格式错误');
                }
                $guid = getGUID();
                $header = [
                        'MessageReferenceNumber' => $guid, //报文参考号
                        'DocumentName' => $DocumentName,
                        'DocumentVersionNumber' => '2015WCCYR',
                        'SenderCode' => config('app.logink.uid'),
                        'RecipientCode' => config('app.logink.touid'),
                        'MessageSendingDateTime' => date('YmdHis'),
                        'MessageFunctionCode' => 9
                ];
                $body = $json_arr['Root']['Body'];
                unset($json_arr['Root']['Body']);

                $json_arr['Root']['Header'] = $header;
                $json_arr['Root']['Body'] = $body;

                //将json转换为xml,并且存入文件
                $xml = (new XmlHelper())->output($json_arr);
                $fileRootPath = config('app.logink.fileRootPath');
                if (!is_dir($fileRootPath)) {
                    mkdir($fileRootPath,0755);
                }
                $xmlFile = $fileRootPath.$prefix.'-'.$ShippingNoteNumber.'.xml';
               file_put_contents($xmlFile,$xml);

               //进行入库记录操作
               $insertData = [
                   'type' => $action,
                   'ShippingNoteNumber' => $ShippingNoteNumber, //运单号
                   'MessageReferenceNumber' => $guid,//报文参考号
                   'SenderCode' => config('app.logink.uid'),//我方物流交换码
                   'RecipientCode' => config('app.logink.touid'),//接收方物流交换码
                   'xmljson' => $json,//业务平台传递的json原始数据
                   'xmlFilePath' => $xmlFile,//xml文件存储的地址
                   'status' => 0,// 数据初始化状态并未进行上传只是入库记录操作
                   'msg' => '',//错误记录为空
                   'createTime' => time(),
               ];

               $id = Db::name('log')->insertGetId($insertData); //插入数据并且获取ID

               $res = $loginkHelper->exchangeTransport($xmlFile,$action,$guid, $prefix.'-'.$ShippingNoteNumber.'.xml');
               //返回成功后修改数据库状态，若失败将会在抛出的异常中进行接管并做记录
               if ($res) {
                   Db::name('log')->where('id','eq',$id)->update(['status'=>1,'updateTime'=>time()]);
               } else {
                   exit('程序出现问题，请及时排查修复！');
               }

                return $return->setCode(200)->setMessage('上报数据成功')->setData($res)->asJson();

            } catch (\Exception $e) {
                //如果已经入库之后的报错一般是和交换服务交互的时候报错的，否则不做数据库记录直接返回
                if (isset($id)) {
                    Db::name('log')->where('id','eq',$id)->update(['status'=>2,'updateTime'=>time(),'msg'=>$e->getMessage()]);
                }

                return $return->setCode(101)->setMessage($e->getMessage())->asJson();

            }

        } else {

            return $return->setCode(300)->setMessage('请求方式错误')->asJson();

        }
    }
}
